package com.xiang.controller;

import com.xiang.DBTest;
import com.xiang.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {
    private static Connection connection = null;
    private static PreparedStatement statement = null;
    private static ResultSet query = null;
    private static ArrayList<Object> list = null;

    public static void init() throws Exception {
        connection = DBTest.getConnection();
        statement = connection.prepareStatement("select  * from  user ");
        query = statement.executeQuery();
        list = new ArrayList<>();

        while (query.next()) {
            User user = new User();
            int anInt = query.getInt(1);
            user.setId(anInt);
            String username = query.getString("username");
            user.setUsername(username);
            String sex = query.getString("sex");
            user.setSex(sex);
            int age = query.getInt(4);
            user.setAge(age);
            Date birthday = query.getDate("birthday");
            user.setBirthday(birthday);
            list.add(user);
        }
        System.out.println("init()");
    }

    @RequestMapping("/view1")
    public String getVive1(ModelMap modelMap) throws Exception {
        init();
        modelMap.addAttribute("list", list);
        DBTest.closeResource();
        return "/user/view1";
    }

    @RequestMapping("/view2")
    public String getVive2(Model model) throws Exception {
        connection = DBTest.getConnection();
        init();
        model.addAttribute("list", list);
        DBTest.closeResource();
        return "/user/view2";
    }

    @RequestMapping("/view3")
    public ModelAndView getVive3() throws Exception {
        init();
        ModelAndView andView = new ModelAndView();
        andView.setViewName("/user/view3");
        andView.addObject("list", list);
        return andView;
    }

}
